﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IFTRUE.EIMS.Helper
{
    /// <summary>
    /// 作用：类、对象辅助方法类
    /// 作者：iftrue
    /// 日期：2013-08-19
    /// </summary>
   public class ObjectHelper
   {
       /// <summary>
       /// 获取类的字段名称和值
       /// </summary>
       /// <typeparam name="T">类</typeparam>
       /// <param name="t">对象</param>
       /// <returns></returns>
       public static string GetNameAndValue<T>(T t)
       {
           string tStr = string.Empty;
           if (t == null)
           {
               return tStr;
           }
           System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
           if (properties.Length <= 0)
           {
               return tStr;
           }
           foreach (System.Reflection.PropertyInfo item in properties)
           {
               string name = item.Name; //名称
               object value = item.GetValue(t, null);  //值

               if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
               {
                   tStr += string.Format("{0}:{1},", name, value);
               }
               else
               {
                   GetNameAndValue(value);
               }
           }
           return tStr;
       }
       /// <summary>
       /// 根据字段名称获取值
       /// </summary>
       /// <typeparam name="T">类</typeparam>
       /// <param name="t">对象</param>
       /// <returns></returns>
       public static string GeValueByName<T>(T t,string fieldName)
       {
           string tStr = string.Empty;
           if (t == null)
           {
               return tStr;
           }
           System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
           if (properties.Length <= 0)
           {
               return tStr;
           }
           foreach (System.Reflection.PropertyInfo item in properties)
           {
               if (item.Name == fieldName)
               {
                   if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                   {
                       tStr = item.GetValue(t, null).ToString();  //值
                   }
                   else
                   {
                       tStr = GetNameAndValue(item.GetValue(t, null));
                   }
                   break;
               }
           }
           return tStr;
       }
    }
}
